# @Author：silence
# @Email：792245022@qq.com
# @Date：2025/3/3 23:35

import urllib.request
import urllib.parse

# https://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname
# post

def creat_request(page):
    url = "https://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname"

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0",
    }

    data = {
        "cname": "北京",
        "pid": "",
        "pageIndex": str(page),
        "pageSize": "10"
    }

    data = urllib.parse.urlencode(data).encode("utf-8")

    return urllib.request.Request(url=url, data=data, headers=headers, method="POST")

def get_content(req):
    response = urllib.request.urlopen(req)
    return response.read().decode("utf-8")

def download(content, page):
    path = f"kfc-{page}.json"
    with open(path, "w", encoding="utf-8") as fw:
        fw.write(content)
    print(f"第{page}页爬取完成！")

if __name__ == "__main__":
    start_page = int(input("请输入开始爬取的页码："))
    end_page = int(input("请输入结束爬取的页码："))

    for page in range(start_page, end_page + 1):
        # 获取请求
        req = creat_request(page)
        # 获取响应的数据
        content = get_content(req)
        # 下载数据
        download(content, page)
